//
//  ModelChoiceViewController.m
//  YinHang
//
//  Created by 张亚哲 on 14/10/25.
//  Copyright (c) 2014年 孙彦鹏. All rights reserved.
//

#import "ModelChoiceViewController.h"
#import "ModelCollectionCell.h"
#import "ModelChoiceButton.h"
#import "ModelData.h"
#import "ModelDataList.h"

#import "DropDownListView.h"//下拉菜单

#define MAX_ROW @"1000"

@interface ModelChoiceViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,DropDownChooseDataSource,DropDownChooseDelegate,ASIHTTPRequestDelegate,ModelDataListServiceDelegate>{
    
    UICollectionView *_collectionView;
    
    NSMutableArray *arr;//数据源
    NSMutableArray *arr1;//单选设置
    
    NSMutableArray *imgArr;
    NSMutableArray *modelArr;//模板类型
    
    NSMutableArray *modelList;//模板列表
    MBProgressHUD *postHud;
    //
    ASIHTTPRequest *getModelListRequest;//获取模板类型名称
    ASIHTTPRequest *postChooseRequest;//获取不同类别模板
    
    ASIFormDataRequest *getState;//获取状态
    ASIFormDataRequest *choiceState;//提交状态
    
    NSString * selectTid;
    NSString * startId;
    
    ModelDataList *modelService;
}

@end

@implementation ModelChoiceViewController


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self getModelList];
    [self getState];
    modelService = [[ModelDataList alloc]init];
    modelService.delegate = self;
    
    //[_collectionView headerBeginRefreshing];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    //测试
    arr = [NSMutableArray arrayWithObjects:@"on",@"on",@"1on",@"on",@"on",@"1on",@"on",@"3on",@"on",@"on",@"on",@"on",@"1on",@"on",@"on",@"1on",nil];
    self.navigationItem.title = @"模板选择";
    arr1 = [NSMutableArray array];
    for (int i = 0; i <= arr.count; i++) {
        imgArr[i] = [UIImage imageNamed:@"choosebox.png"];
    }
    UIButton *leftBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 20, 30)];
    [leftBtn setBackgroundImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:leftBtn];
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    negativeSpacer.width = - 10;
    if (ios7) {
        self.navigationItem.leftBarButtonItems = @[negativeSpacer,leftBarButtonItem];
    }else{
        self.navigationItem.leftBarButtonItems = @[leftBarButtonItem];
    }
    
    [self setCollectionUI];
    [self setupRefresh];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark CustomMethod

-(void)getState{
    // 检查网络
    if (![Constants isExistenceNetwork]) {
        
    } else {
        if (!postHud || postHud.hidden == YES) {
            // 提示正在加载数据...
            if (!postHud) {
                postHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                postHud.labelText = @"正在加载，请稍后...";
            }else{
                postHud.hidden = NO;
            }
        }
        getState = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:API_STR]];
        getState.requestMethod = @"POST";
        // 设置超时时间
        getState.timeOutSeconds = 60;
        getState.delegate = self;
        // 设置参数
        NSString *action =@"uidmoban";
        NSDictionary *paramsDict =  @{@"uid":UNAME};
        NSString *paramsStr = [NSString JSONString:paramsDict];
        NSString *result = [NSString stringWithFormat:TEMPLATE_PARAMSTR, action,paramsStr];
        NSData *paramsData = [result toGBKEncodingData];
        getState.postBody = [paramsData mutableCopy];
        
        [getState startAsynchronous];
    }
}
//getmodel
-(void)getModelList{
    // 检查网络
    if (![Constants isExistenceNetwork]) {
        
    } else {
        if (!postHud || postHud.hidden == YES) {
            // 提示正在加载数据...
            if (!postHud) {
                postHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                postHud.labelText = @"正在加载，请稍后...";
            }else{
                postHud.hidden = NO;
            }
        }
        getModelListRequest = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:API_STR]];
        getModelListRequest.requestMethod = @"POST";
        // 设置超时时间
        getModelListRequest.timeOutSeconds = 60;
        getModelListRequest.delegate = self;
        // 设置参数
        NSString *action =@"MoBanTypelist";
        NSDictionary *paramsDict =  @{};
        NSString *paramsStr = [NSString JSONString:paramsDict];
        NSString *result = [NSString stringWithFormat:TEMPLATE_PARAMSTR, action,paramsStr];
        NSData *paramsData = [result toGBKEncodingData];
        getModelListRequest.postBody = [paramsData mutableCopy];
        
        [getModelListRequest startAsynchronous];
    }
}
//获取模板
-(void)postChoose:(NSString *)tid{
    // 检查网络
    if (![Constants isExistenceNetwork]) {
        
    } else {
        if (!postHud || postHud.hidden == YES) {
            // 提示正在加载数据...
            if (!postHud) {
                postHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                postHud.labelText = @"正在加载，请稍后...";
            }else{
                postHud.hidden = NO;
            }
        }
        postChooseRequest = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:API_STR]];
        postChooseRequest.requestMethod = @"POST";
        // 设置超时时间
        postChooseRequest.timeOutSeconds = 60;
        postChooseRequest.delegate = self;
        // 设置参数
        NSString *action =@"mobanlist";
        NSDictionary *paramsDict =  @{@"tid":tid,@"pagenow":@"1",@"pagesize":@"1000"};
        NSString *paramsStr = [NSString JSONString:paramsDict];
        NSString *result = [NSString stringWithFormat:TEMPLATE_PARAMSTR, action,paramsStr];
        NSData *paramsData = [result toGBKEncodingData];
        postChooseRequest.postBody = [paramsData mutableCopy];
        
        [postChooseRequest startAsynchronous];
    }
}

//dropViewList
-(void)addDropView{
    DropDownListView * dropDownView = [[DropDownListView alloc] initWithFrame:CGRectMake(127,5, 154, 30) dataSource:self delegate:self];
    dropDownView.layer.cornerRadius = 5.0;
    dropDownView.mSuperView = self.view;
    [self.view addSubview:dropDownView];
}

//collection
-(void)setCollectionUI{
    //collectionView设置
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    [layout setScrollDirection:UICollectionViewScrollDirectionVertical];
    layout.itemSize = CGSizeMake(150,187); //CGSizeMake(200 , 200);layout.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5);layout.minimumLineSpacing = 5;
    _collectionView = [[UICollectionView alloc]initWithFrame:IPHONE5 ?  CGRectMake(0, 50, 320, 568 - 50 - 64) : CGRectMake(0, 50, 320, 480 - 64 - 50 )collectionViewLayout:layout];
    
    _collectionView.bounces = YES;
    //_collectionView.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, 0, 0);
    _collectionView.alwaysBounceVertical = YES;
    
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    _collectionView.backgroundColor = [UIColor clearColor];
    [_collectionView registerClass:[ModelCollectionCell class] forCellWithReuseIdentifier:@"ModelCollectionCell"];
    
    [self.view addSubview:_collectionView];
}

//返回
-(void)back{
    [self cancelRequest];
    modelService = nil;
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark -- dropDownListDelegate
-(void) chooseAtSection:(NSInteger)section index:(NSInteger)index
{
    [arr removeAllObjects];
    [arr1 removeAllObjects];
    [self setupRefresh];
    modelService.pageInfo.pageno = @"1";
    NSLog(@"选了section:%ld ,index:%ld",section,index);
    selectTid = modelArr[index][@"tid"];
    //[self postChoose:modelArr[index][@"tid"]];
    [_collectionView headerBeginRefreshing];
    
}

#pragma mark -- dropdownList DataSource
-(NSInteger)numberOfSections
{
    return 1;
}
-(NSInteger)numberOfRowsInSection:(NSInteger)section
{
    return [modelArr count];
}
-(NSString *)titleInSection:(NSInteger)section index:(NSInteger) index
{
    return modelArr[index][@"tname"];
}
-(NSInteger)defaultShowSection:(NSInteger)section
{
    return 0;
}

#pragma mark CollectionViewDelegateMethods

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    //static NSString *identify = @"cell";
    
    //ModelCollectionCell *cell = [[ModelCollectionCell alloc]init];
    ModelCollectionCell * cell = (ModelCollectionCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"ModelCollectionCell" forIndexPath:indexPath];
    ModelChoiceButton *btn = (ModelChoiceButton *)[cell.contentView viewWithTag:1];
    //缓存model图片
    [btn buttonWithUrl:modelService.pageInfo.dataArr[indexPath.item][@"picture"]];
    btn.imageView.contentMode = UIViewContentModeScaleAspectFit;
    
    btn.index = indexPath;
    [btn addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
    cell.backgroundColor = [UIColor clearColor];
    UIImageView *imgView = (UIImageView *)[cell.contentView viewWithTag:2];
    UILabel *lbl = (UILabel *)[cell.contentView viewWithTag:3];
    UIView *Cellview = [cell.contentView viewWithTag:4];
    
    if ([modelService.pageInfo.dataArr[indexPath.item][@"id"] isEqualToString:startId]) {
        [arr1 addObject:indexPath];
    }
    if ([self contenthsHas:arr1 index:indexPath.item]) {
        lbl.text = @"已使用";
        lbl.textColor = [UIColor redColor];
        [cell.contentView setBackgroundColor:[UIColor clearColor]];
        imgView.image = [UIImage imageNamed:@"Modelcheck.png"];
        Cellview.backgroundColor = APP_COLOR;
    }else{
        lbl.text = @"启用";
        [cell.contentView setBackgroundColor:[UIColor clearColor]];
        imgView.image = [UIImage imageNamed:@"Modeluncheck.png"];
        lbl.textColor = [UIColor blackColor];
        Cellview.backgroundColor = [UIColor whiteColor];
    }
    return cell;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
//    if (!modelList || modelList.count != 0) {
//        return modelList.count;
//    }else{
//        return 0;
//    }
    if (modelService.pageInfo.dataArr.count != 0) {
        return modelService.pageInfo.dataArr.count;
    }else{
        return 0;
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(150,187);
}
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(3, 3, 3, 3);
}
//UICollectionView被选中时调用的方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    [arr1 removeAllObjects];
    if (![self contenthsHas:arr1 index:indexPath.item]) {
        [arr1 addObject:indexPath];
    }
    if (arr1.count > 1) {
        [arr1 removeObjectAtIndex:0];
    }
    
    [self postSelectWithId:(NSString*) modelService.pageInfo.dataArr[indexPath.item][@"id"]];
    startId = modelService.pageInfo.dataArr[indexPath.item][@"id"];
    NSLog(@"%i",indexPath.item);
//    UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
//    UIImageView *img = (UIImageView *)[cell.contentView viewWithTag:2];
//    img.image = [UIImage imageNamed:@"Modeluncheck.png"];
//    UILabel *lbl = (UILabel *)[cell.contentView viewWithTag:3];
//    lbl.text = @"启用";
    //[collectionView reloadItemsAtIndexPaths:@[indexPath]];
    [collectionView reloadData];
}
//返回这个UICollectionView是否可以被选择
-(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

-(void)click:(id)sender{
    ModelChoiceButton *btn = sender;
    //    UICollectionViewCell *cell = (UICollectionViewCell *)btn.superview;
    //    //NSIndexPath *indexPath = [[NSIndexPath alloc]initWithIndex:btn.tag];
    //    UILabel *lbl = (UILabel *)[cell.contentView viewWithTag:2];
    //    lbl.text = @"select";
    
    NSLog(@"%i",btn.index.item);
}
//检查数组是否包含item
-(BOOL)contenthsHas:(NSMutableArray *)array index:(NSInteger) item{
    for (NSIndexPath *key  in array) {
        if (key.item == item) {
            return YES;
        }
    }
    return NO;
}
//发送改变选中状态
-(void)postSelectWithId:(NSString*)idstr{
    // 检查网络
    if (![Constants isExistenceNetwork]) {
        
    } else {
        if (!postHud || postHud.hidden == YES) {
            // 提示正在加载数据...
            if (!postHud) {
                postHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                postHud.labelText = @"正在加载，请稍后...";
            }else{
                postHud.hidden = NO;
            }
        }
        choiceState = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:API_STR]];
        choiceState.requestMethod = @"POST";
        // 设置超时时间
        choiceState.timeOutSeconds = 60;
        choiceState.delegate = self;
        // 设置参数
        NSString *action =@"mobanchiclk";
        NSDictionary *paramsDict =  @{@"id":idstr,@"uid":UNAME};
        NSString *paramsStr = [NSString JSONString:paramsDict];
        NSString *result = [NSString stringWithFormat:TEMPLATE_PARAMSTR, action,paramsStr];
        NSData *paramsData = [result toGBKEncodingData];
        choiceState.postBody = [paramsData mutableCopy];
        
        [choiceState startAsynchronous];
    }
}

#pragma mark - ASIHttpRequestDelegate method

- (void)requestFinished:(ASIHTTPRequest *)request {
    NSLog(@"%@",request.responseString);
    postHud.hidden = YES;
    NSError *err;
    NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[request.responseString dataForUTF8] options:NSJSONReadingAllowFragments error:&err];
    
    // 1. 是否解析有错误
    if (!err) {
        
        // 2. 判断错误码
        NSInteger errorCode = [result[@"errorCode"]integerValue];
        if (errorCode == 0) {
           
            //改变状态
            if (request == choiceState) {
                [SVProgressHUD showSuccessWithStatus:result[@"errorMsg"]];
                return;
            }
             // 2.1 获取"info"
            NSDictionary *info = result[@"info"];
            NSLog(@"%@",info);
            
            //NSInteger totalCount = [info[@"total"]integerValue];
            //获取数据
            if (request == getState) {
                startId = info[@"id"];
                NSInteger row = 0;
                for (int i = 0; i < modelList.count; i++) {
                    if ( [modelList[i][@"tid"] isEqualToString:startId]) {
                        row = i;
                    }
                }
               // [self collectionView:_collectionView didSelectItemAtIndexPath:[NSIndexPath indexPathForItem:row inSection:0]];
            }
            NSArray *list = info[@"data"];
            if (request == getModelListRequest) {
                modelArr = [list mutableCopy];
                for (int i = 0; i <= modelArr.count; i++) {
                    imgArr[i] = [UIImage imageNamed:@"choosebox.png"];
                }
                [self addDropView];
                //[self postChoose:modelArr[0][@"tid"]];
                selectTid = modelArr[0][@"tid"];
                modelService.tid = modelArr[0][@"tid"];
                [_collectionView headerBeginRefreshing];
                //[modelService pageQuery];
            }else if(request == postChooseRequest){
                modelList = info[@"data"];
                [_collectionView reloadData];
            }
            
            
            postHud.hidden = YES;
            
        }else {
            NSString *dataStr = result[@"info"][@"data"];
            if ([dataStr isEqualToString:@"0"]) {
                if ([result[@"errorMsg"] isEqualToString:@"该条件下为得到任何数据"]){
                    [SVProgressHUD showErrorWithStatus:@"该条件下为得到任何数据"];
                }
            }
            postHud.hidden = YES;
        }
        
    }else {
        postHud.hidden = YES;
        [SVProgressHUD showErrorWithStatus:@"数据解析出错！"];
    }
  
}

- (void)requestFailed:(ASIHTTPRequest *)request{
    postHud.hidden = YES;
    [SVProgressHUD showErrorWithStatus:@"服务器无法访问，请稍后再试!"];
    
}

// 取消网络访问
- (void)cancelRequest {
    [getModelListRequest cancel];
    [postChooseRequest cancel];
}

/**
 *  集成刷新控件
 */
- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [_collectionView addHeaderWithTarget:self action:@selector(headerRereshing)];
    /* 自动刷新(一进入程序就下拉刷新) */
    //[_tableView headerBeginRefreshing];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [_collectionView addFooterWithTarget:self action:@selector(footerRereshing)];
}

#pragma mark 开始进入刷新状态
- (void)headerRereshing
{
    // 刷新表格
    if (modelService.isQuery ||![Constants isExistenceNetwork]) {
        [_collectionView reloadData];
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [_collectionView headerEndRefreshing];
        return;
    }
    
    // 下拉刷新 （请求第一页数据）
    modelService.pageInfo.hasMoreData = YES;
    // 每次必须重置下 否则会数据混乱
    modelService.pageInfo.pageno = @"1";
    modelService.tid = selectTid;
    [modelService pageQuery];
}

- (void)footerRereshing
{
    // 检查网络
    if (![Constants isExistenceNetwork]) {
        
        // 刷新表格
        [_collectionView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [_collectionView footerEndRefreshing];
        
        return;
    }
    
    // 如果正在查询 或 没有更多数据了
    //    NSLog(@"%i",linkService.isQuery);
    //    NSLog(@"%i",linkService.pageInfo.hasMoreData);
    if (modelService.isQuery || !modelService.pageInfo.hasMoreData) {
        // 2. 1秒后刷新表格UI
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 刷新表格
            [_collectionView reloadData];
            
            // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
            [_collectionView footerEndRefreshing];
            
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            hud.labelText = @"没有更多数据了";
            [hud hide:YES afterDelay:1];
        });
        
        //linkService.pageInfo.hasMoreData = YES;
        
        return;
    }
    
    // 如果还有更多数据 请求下一页
    [modelService.pageInfo nextPage];
    [modelService pageQuery];
}
-(void)dealloc{
    [postChooseRequest cancel];
    postChooseRequest = nil;
    [getModelListRequest cancel];
    getModelListRequest = nil;
    postHud = nil;
    modelService = nil;
    _collectionView = nil;
}
#pragma mark - QuestionService Delegate

- (void)didRecieveData{
    [_collectionView headerEndRefreshing];
    [_collectionView footerEndRefreshing];
    [_collectionView reloadData];
}
- (void)didRecieveMsg{
    [_collectionView headerEndRefreshing];
    [_collectionView footerEndRefreshing];
    [_collectionView reloadData];
}

@end
